package com.znz.service;

import com.znz.domain.Project;
import com.znz.domain.Thospital;
import com.znz.domain.ThospitalProjectAgreement;
import com.znz.domain.Torder;
import com.znz.util.common.Page;
import com.znz.util.common.Tools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: johnson
 * Date: 4/26/15
 * Time: 2:01 下午
 */

@Service
public class HospitalService {

	//TODO 保存医院信息    创建医院账户

	/**
	 * @param hospital 医院对象
	 * @return JSON
	 */
	public JSONObject addHospital(String hospital) {
		//保存医院的基础信息
		JSONObject hospitalDetail = JSONObject.fromObject(hospital);//医院基础信息
		Thospital thospital = getThospital(hospitalDetail);
		int indexnum = 0;
		while (getObjectjson("projectID", hospitalDetail, indexnum) != null) {
			indexnum = indexnum + 1;
		}
//		保存医院和合约项目之间的关系
		for (int i = 0; i < indexnum; i++) {
			saveThospitalProjectAgreeement(hospitalDetail, thospital, i,false);
		}
		return new JSONObject();
	}

	/**
	 * 保存医院信息
	 * @param hospitalDetail
	 * @return
	 */
	private Thospital getThospital(JSONObject hospitalDetail) {
		Thospital thospital = new Thospital();
		thospital.setHospitalName(hospitalDetail.getString("hospitalName"));
//		thospital.setCertification(hospitalDetail.getString("hospitalAddress"));
		thospital.setCity(hospitalDetail.getString("city"));
//		thospital.setContract_deadline(hospitalDetail.getString("contractDeadline"));
		thospital.setCreateTime(new Date());
		thospital.setFeaturesProject(hospitalDetail.getString("featuresProject"));
		thospital.setHospitalAddress(hospitalDetail.getString("hospitalAddress"));
		thospital.setHospitalAlias(hospitalDetail.getString("hospitalAlias"));
		thospital.setHospitalNature(hospitalDetail.getInt("hospitalNature"));
		thospital.setHospitalUrl(hospitalDetail.getString("hospitalUrl"));
		thospital.setPhone(hospitalDetail.getString("phone"));
		thospital.setProjectLevel(hospitalDetail.getInt("projectLevel"));
		thospital.setProvince(hospitalDetail.getString("province"));
		thospital.setStatus(1);
		thospital.setVipFlag(0);
		thospital.setUpdateTime(new Date());
//		联系人的添加
		JSONArray contactList = getContactJsonArray(hospitalDetail);
		thospital.setContacts(contactList.toString());
		thospital.persist();
		return thospital;
	}

	/**
	 * 保存医院与合约项目的之间的关系
	 *
	 * @param hospitalDetail
	 * @param thospital
	 * @param i
	 */
	private void saveThospitalProjectAgreeement(JSONObject hospitalDetail, Thospital thospital, int i,boolean flag) {
            ThospitalProjectAgreement thospitalProjectAgreement = new ThospitalProjectAgreement();
            thospitalProjectAgreement.setHospitalId(thospital);
            thospitalProjectAgreement.setProjectName(getObjectjson("projectName", hospitalDetail, i).toString());
            thospitalProjectAgreement.setCommission(getObjectjson("commission", hospitalDetail, i).toString());
            Long projectId=Long.parseLong(getObjectjson("projectID", hospitalDetail, i).toString());
            thospitalProjectAgreement.setProjectID(Project.findProject(projectId));
            thospitalProjectAgreement.persist();
	}


	/**
	 * 获取联系人拼接json数据
	 *
	 * @param hospitalDetail
	 * @return
	 */
	private JSONArray getContactJsonArray(JSONObject hospitalDetail) {
		JSONArray contactList = new JSONArray();
		JSONObject contact = new JSONObject();
		contact.put("contactsName", hospitalDetail.getString("contactsName"));
		contact.put("gender", hospitalDetail.getString("gender"));
		contact.put("contactsPhone", hospitalDetail.getString("contactsPhone"));
		contact.put("position", hospitalDetail.getString("position"));
		contact.put("email", hospitalDetail.getString("email"));
		contact.put("qq", hospitalDetail.getString("qq"));
		contact.put("wechat", hospitalDetail.getString("wechat"));
		contactList.add(contact);
		return contactList;
	}

	private Object getObjectjson(String key, JSONObject hospitalDetail, int indexnum) {
		return hospitalDetail.get(key + "[" + indexnum + "]");
	}


	//TODO 查看所有已经注册但未审核的医院信息列表 医院审核

	/**
	 * @param hospitalName 医院名称
	 * @param state        医院状态
	 * @return
	 */
	public Page<Thospital> getUnApproveHospitalListByName(String hospitalName, int state,Page<Thospital> page) {
        try{
            StringBuilder where=new StringBuilder();
            List<Object> params=new ArrayList<Object>();
            if(null!=hospitalName){
                where.append(" o.hospitalName=? ");
                params.add("%"+hospitalName+"%");
            }
            page.setTotal((int)Thospital.countThospitals());
            List<Thospital> thospitalList=Thospital.getunApproveHospitalList(where.toString(),params,page.getOffset(),page.getOffset()+page.getLimit());
            page.setRows(thospitalList);
            return page;
        }catch (Exception e){
             e.printStackTrace();
        }
		return page;
	}

	;
	//TODO 根据部位查询项目     医院审核

	/**
	 * @param partId 部位ID
	 * @return
	 */
	public List<Project> getProjectListByPart(Long partId) {
        List<Project> projectList=new ArrayList<Project>();
        List<Object> params=new ArrayList<Object>();
        StringBuilder  where=new StringBuilder();
        if(null!=partId){
            where.append(" and o.part.id=? ");
            params.add(partId);
        }
        try {
            projectList= Torder.getProjectAllByPartId(where.toString(), params);
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return   projectList;
	}

    /**
     * @param hospital
     * @return
     */
    public boolean editeHospital(String hospital){
       try {
           JSONObject hospitalDetail=JSONObject.fromObject(hospital);
           Thospital thospital=getThospital(hospitalDetail);
           thospital.merge();
       }catch (Exception e){
             e.printStackTrace();
       }
        return false;
    }

    public ThospitalProjectAgreement getThospitalProjectAgreement(JSONObject ThospitalProjectAgreement,Thospital thospital,int i){
                ThospitalProjectAgreement thospitalProjectAgreement=new ThospitalProjectAgreement();
                thospitalProjectAgreement.setHospitalId(thospital);
                thospitalProjectAgreement.setProjectName(ThospitalProjectAgreement.getString("projectName"));
                thospitalProjectAgreement.setCommission(ThospitalProjectAgreement.getString("commission"));
                Long projectId=Long.parseLong(getObjectjson("projectID", ThospitalProjectAgreement, i).toString());
                thospitalProjectAgreement.setProjectID(Project.findProject(projectId));
                thospitalProjectAgreement.merge();
        return  thospitalProjectAgreement;
    }




	/**
	 *分页获取医院列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public Page<Thospital> getResourcePage(Page<Thospital> page) throws  Exception{
		page.setTotal((int) Thospital.countThospitals());
		page.setRows(
				Thospital.findThospitalEntries(
						page.getOffset(),  //
						page.getOffset() + page.getLimit(), page.getSort(), page.getOrder()
				)
		);
		return page;
	}
    public boolean removeHospitalById(Long hospitalId){
       boolean flag=false;
       Thospital thospital=Thospital.findThospital(hospitalId);
       Long thId=null;
       if(null!=thospital){
           thId=thospital.getId();
           thospital.remove();
           try {
               ThospitalProjectAgreement.removeProjectByHospitalId(thId);
               flag=true;
           } catch (Exception e) {
               e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
               flag=false;
           }
       }
      return flag;
    };
   public Thospital getThospitalById(Long hospitalId){
        Thospital thospital=Thospital.findThospital(hospitalId);
        if(null!=thospital){
              return  thospital;
        }
       return null;
   }

    public List<ThospitalProjectAgreement> getThospitalProjectAgreementListByHospitalId(Long hospitalId) throws Exception {
        String where = " and o.hospitalId=? ";
        List<Object> param = new ArrayList<Object>();
        param.add(hospitalId);
        List<ThospitalProjectAgreement> thospitalProjectAgreementList = ThospitalProjectAgreement.getThospitalProjectAgreementByWhere(where,param);
        return null;
    }

    /**
     * 方法说明:医院认证(审核通过)
     * @param hospitalId  医院ID
     * @return
     */
    public boolean approveHospital(Long hospitalId){
        boolean flag=false;
        try {
            if(null!=hospitalId){
                flag=Thospital.approveHospital(hospitalId);
            }
            return flag;
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

        }
         return  flag;
    }


}
